package com.huilian.iotbox.admin.service.impl;

import com.huilian.iotbox.admin.service.ActivityOrderRefundService;
import com.huilian.iotbox.data.common.RedisKey;
import com.huilian.iotbox.data.config.AgencyConfig;
import com.huilian.iotbox.data.config.MiddlewareConfig;
import com.huilian.iotbox.data.dto.ActivityOrderRefundDto;
import com.huilian.iotbox.data.enums.FunctionEnum;
import com.huilian.iotbox.data.enums.RefundStatusEnum;
import com.huilian.iotbox.data.enums.RequestStatus;
import com.huilian.iotbox.data.service.ErrorLogCommonService;
import com.huilian.iotbox.data.utils.HttpUtils;
import com.huilian.iotbox.data.utils.HttpsMain;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author 谢洛涛
 * @date 2022/6/28 14:15
 */
@Slf4j
@Service
public class ActivityOrderRefundServiceImpl implements ActivityOrderRefundService {
    @Autowired
    private RedisTemplate<String, Serializable> redisCacheTemplate;
    @Autowired
    private ErrorLogCommonService errorLogCommonService;
    @Autowired
    private AgencyConfig agencyConfig;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public void queryActivityOrderRefund() {
        Set<String> keys = redisCacheTemplate.keys("*" + RedisKey.ACTIVITY_ORDER_REFUND_ + "*");
        log.info("-----------------轮询杀拼团等活动退款订单状态查询-开始：{}-------------------", keys.size());
        ActivityOrderRefundDto item = null;
        for (String key : keys) {
            int index = key.indexOf(RedisKey.ACTIVITY_ORDER_REFUND_);
            key = key.substring(index);
            log.info("轮训订单key{}", key);
            try {
                item = (ActivityOrderRefundDto) redisCacheTemplate.opsForValue().get(key);
            } catch (Exception e) {
                errorLogCommonService.writerInfoException("杀拼团等活动退款缓存查询失败", item, e);
            }
            if (item == null) {
                continue;
            }
            //查询退款订单
            try {
                Map<String, Object> form = new HashMap<>();
                form.put("HlMerchantId", item.getMerchantId());
                form.put("OutRefundNo", item.getOutRefundNo());
                String param = HttpUtils.format(agencyConfig, form, FunctionEnum.ORDER_REFUND_QUERY);
                String response = HttpsMain.httpsReq(MiddlewareConfig.orderUrl, param);
                log.info("请求响应结果{}", response);
                //延签并返回map值
                final Map<String, Object> result = HttpUtils.getResultData(response);
                final String status = (String) result.get("status");
                final String code = (String) result.get("code");
                if (status.equals(RequestStatus.SUCCESS.getCode()) && code.equals(RequestStatus.SUCCESS_CODE.getCode())) {
                    Map<String, String> resMap = (Map<String, String>) result.get("data");
                    ActivityOrderRefundDto activityOrderRefundDto = new ActivityOrderRefundDto();
                    activityOrderRefundDto.setOutRefundNo(resMap.get("outRefundNo"));
                    activityOrderRefundDto.setOutTradeNo(resMap.get("outTradeNo"));
                    activityOrderRefundDto.setRefundOrderNo(resMap.get("refundOrderNo"));
                    activityOrderRefundDto.setTradeStatus(resMap.get("tradeStatus"));
                    activityOrderRefundDto.setMerchantId(resMap.get("hlMerchantId"));
                    activityOrderRefundDto.setRefundAmount(new BigDecimal(resMap.get("refundAmount")));
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    if (resMap.get("gmtRefundment") != null) {
                        activityOrderRefundDto.setGmtRefundment(df.parse(resMap.get("gmtRefundment")));
                    }
                    if (!RefundStatusEnum.REFUNDING.getCode().equals(activityOrderRefundDto.getTradeStatus())) {
                        log.info("申请退款成功后发送MQ：{}", System.currentTimeMillis());
                        CorrelationData correlationData = new CorrelationData(item.getRefundOrderNo());
                        rabbitTemplate.convertAndSend("iotBox-query-activity-order-Refund", "iotBox-query-activity-order-Refund.iotBoxQueryActivityOrderRefund", activityOrderRefundDto, correlationData);
                    }
                }

            } catch (Exception e) {
                errorLogCommonService.writerInfoException("查询杀拼团等活动退款订单异常", item, e);
            }
        }
        log.info("-----------------轮询杀拼团等活动退款订单状态查询-结束：-------------------");
    }

}
